package com.zhaorl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhaorl.domain.LoginUser;
import com.zhaorl.domain.User;
import com.zhaorl.mapper.MenuMapper;
import com.zhaorl.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Description 重写UserDetailsService内的UserDetailsServiceImpl认证方法
 * @Author zhaorl
 * @Date 2023/3/28 15:50
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * @description 根据名字获取用户信息重写
     * @param userName
     * @return UserDetails
     * @author zhaorl
     * @date 2023/3/28 15:51
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        // 获取用户信息
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName,userName);
        // 获取到的user对象
        User user = userMapper.selectOne(lambdaQueryWrapper);
        // 判断该对象是否存在
        if (Objects.isNull(user)){
            // 对象是个空的
            throw new RuntimeException("用户名不存在");
        }
        // 同时获取用户的权限信息 TODO
        List<String> authoritieslist = menuMapper.selectPermsByUserId(user.getId());
//        List<String> authoritieslist = new ArrayList<>(Arrays.asList("test"));
        // 将用户的基本信息和用户的权限信息封装成userdtails对象返回;
        return new LoginUser(user,authoritieslist);
    }
}
